import { Button, View, Text } from "@tarojs/components";
import { useEffect, useState, useCallback, useMemo } from "react";
import { Gem, Card, UserPanel } from '@/types/global';
import "./index.less";

interface BuyCardModalProps {
  close: () => void;
  card: Card; // 要购买的卡片
  userPanel: UserPanel; // 当前玩家面板数据
  gemSource?: Gem[]; // 初始宝石列表
  onConfirm: (gemIds: string[]) => void; // 确认购买的回调函数
}

export default function BuyCardModal({ 
  close, 
  card,
  userPanel,
  gemSource, 
  onConfirm
}: BuyCardModalProps) {
  const [selectedGemIds, setSelectedGemIds] = useState<string[]>([]); // 存储选中的宝石ID

  // 计算扣除折扣后需要的宝石数量
  const requiredGems = useMemo(() => {
    return {
      red: Math.max(0, card.costRed - userPanel.discountRed),
      blue: Math.max(0, card.costBlue - userPanel.discountBlue),
      green: Math.max(0, card.costGreen - userPanel.discountGreen),
      white: Math.max(0, card.costWhite - userPanel.discountWhite),
      black: Math.max(0, card.costBlack - userPanel.discountBlack),
      pink: Math.max(0, card.costPink), // 粉色宝石没有折扣
      gold: 0 // 金色宝石用于补足
    };
  }, [card, userPanel]);

  // 计算总需求
  const totalRequired = useMemo(() => {
    return requiredGems.red + requiredGems.blue + requiredGems.green + 
           requiredGems.white + requiredGems.black + requiredGems.pink;
  }, [requiredGems]);

  // 获取玩家拥有的宝石
  const playerGems = useMemo(() => {
    // 过滤掉已经选择用于支付的宝石
    return userPanel.collectedGems;
  }, [userPanel.collectedGems]);

  // 处理宝石点击
  const handleGemClick = useCallback((gemId: string) => {
    setSelectedGemIds(prev => {
      // 如果已选中，则取消选择
      if (prev.includes(gemId)) {
        return prev.filter(id => id !== gemId);
      }
      
      // 添加到选中列表
      return [...prev, gemId];
    });
  }, []);

  // 验证选择的宝石是否符合要求
  const validateSelection = useCallback(() => {
    // 统计选中宝石各颜色数量
    const selectedCounts = {
      red: 0,
      blue: 0,
      green: 0,
      white: 0,
      black: 0,
      pink: 0,
      gold: 0
    };
    
    selectedGemIds.forEach(gemId => {
      const gem = playerGems.find(g => g.id === gemId);
      if (gem) {
        selectedCounts[gem.color as keyof typeof selectedCounts]++;
      }
    });
    
    // 检查各颜色是否满足需求（金色宝石可以作为任意颜色使用）
    let goldUsed = 0;
    
    // 检查红色
    if (selectedCounts.red < requiredGems.red) {
      const needed = requiredGems.red - selectedCounts.red;
      if (goldUsed + needed <= selectedCounts.gold) {
        goldUsed += needed;
      } else {
        return false; // 金色宝石不够补足
      }
    }
    
    // 检查蓝色
    if (selectedCounts.blue < requiredGems.blue) {
      const needed = requiredGems.blue - selectedCounts.blue;
      if (goldUsed + needed <= selectedCounts.gold) {
        goldUsed += needed;
      } else {
        return false; // 金色宝石不够补足
      }
    }
    
    // 检查绿色
    if (selectedCounts.green < requiredGems.green) {
      const needed = requiredGems.green - selectedCounts.green;
      if (goldUsed + needed <= selectedCounts.gold) {
        goldUsed += needed;
      } else {
        return false; // 金色宝石不够补足
      }
    }
    
    // 检查白色
    if (selectedCounts.white < requiredGems.white) {
      const needed = requiredGems.white - selectedCounts.white;
      if (goldUsed + needed <= selectedCounts.gold) {
        goldUsed += needed;
      } else {
        return false; // 金色宝石不够补足
      }
    }
    
    // 检查黑色
    if (selectedCounts.black < requiredGems.black) {
      const needed = requiredGems.black - selectedCounts.black;
      if (goldUsed + needed <= selectedCounts.gold) {
        goldUsed += needed;
      } else {
        return false; // 金色宝石不够补足
      }
    }
    
    // 检查粉色
    if (selectedCounts.pink < requiredGems.pink) {
      const needed = requiredGems.pink - selectedCounts.pink;
      if (goldUsed + needed <= selectedCounts.gold) {
        goldUsed += needed;
      } else {
        return false; // 金色宝石不够补足
      }
    }
    
    // 检查是否使用了过多的金色宝石
    if (goldUsed > selectedCounts.gold) {
      return false;
    }
    
    return true;
  }, [selectedGemIds, playerGems, requiredGems]);

  // 处理确认按钮点击
  const handleConfirm = useCallback(() => {
    if (totalRequired === 0) {
      // 免费获取，直接调用回调
      onConfirm([]);
      close();
      return;
    }
    
    if (validateSelection()) {
      onConfirm(selectedGemIds);
      close();
    } else {
      // 提示用户选择的宝石不符合要求
      // alert('选择的宝石不符合支付要求，请重新选择');
    }
  }, [totalRequired, validateSelection, onConfirm, selectedGemIds, close]);

  // 重置选择
  const handleReset = useCallback(() => {
    setSelectedGemIds([]);
  }, []);

  // 渲染需求宝石
  const renderRequiredGems = useMemo(() => {
    const gems: JSX.Element[] = [];
    
    // 添加红色宝石需求
    for (let i = 0; i < requiredGems.red; i++) {
      gems.push(
        <View key={`req-red-${i}`} className='gem-item red-gem'>
          <Text className='gem-text'>红</Text>
        </View>
      );
    }
    
    // 添加蓝色宝石需求
    for (let i = 0; i < requiredGems.blue; i++) {
      gems.push(
        <View key={`req-blue-${i}`} className='gem-item blue-gem'>
          <Text className='gem-text'>蓝</Text>
        </View>
      );
    }
    
    // 添加绿色宝石需求
    for (let i = 0; i < requiredGems.green; i++) {
      gems.push(
        <View key={`req-green-${i}`} className='gem-item green-gem'>
          <Text className='gem-text'>绿</Text>
        </View>
      );
    }
    
    // 添加白色宝石需求
    for (let i = 0; i < requiredGems.white; i++) {
      gems.push(
        <View key={`req-white-${i}`} className='gem-item white-gem'>
          <Text className='gem-text'>白</Text>
        </View>
      );
    }
    
    // 添加黑色宝石需求
    for (let i = 0; i < requiredGems.black; i++) {
      gems.push(
        <View key={`req-black-${i}`} className='gem-item black-gem'>
          <Text className='gem-text'>黑</Text>
        </View>
      );
    }
    
    // 添加粉色宝石需求
    for (let i = 0; i < requiredGems.pink; i++) {
      gems.push(
        <View key={`req-pink-${i}`} className='gem-item pink-gem'>
          <Text className='gem-text'>粉</Text>
        </View>
      );
    }
    
    return gems;
  }, [requiredGems]);

  // 渲染玩家拥有的宝石
  const renderPlayerGems = useMemo(() => {
    return playerGems.map((gem, index) => {
      const isSelected = selectedGemIds.includes(gem.id);
      return (
        <View
          key={`player-${gem.id}-${index}`}
          className={`gem-item ${gem.color}-gem ${isSelected ? 'selected' : ''}`}
          onClick={() => !isSelected && handleGemClick(gem.id)}
        >
          <Text className='gem-text'>
            {gem.color === 'red' && '红'}
            {gem.color === 'blue' && '蓝'}
            {gem.color === 'green' && '绿'}
            {gem.color === 'white' && '白'}
            {gem.color === 'black' && '黑'}
            {gem.color === 'pink' && '粉'}
            {gem.color === 'gold' && '金'}
          </Text>
          {isSelected && <View className='selected-overlay'></View>}
        </View>
      );
    });
  }, [playerGems, selectedGemIds, handleGemClick]);

  return (
    <View className='buyCardModalContainer'>
      <View className='modalHeader'>
        <Text className='headerTitle'>购买卡片</Text>
      </View>
      
      <View className='cardInfo'>
        <Text>卡片ID: {card.id}</Text>
      </View>
      
      <View className='requiredGemsSection'>
        <Text className='sectionTitle'>需要支付的宝石:</Text>
        <View className='gemsContainer'>
          {totalRequired === 0 ? (
            <Text className='freeText'>免费获取</Text>
          ) : (
            renderRequiredGems
          )}
        </View>
      </View>
      
      <View className='playerGemsSection'>
        <Text className='sectionTitle'>你的宝石:</Text>
        <View className='gemsContainer'>
          {renderPlayerGems}
        </View>
      </View>
      
      <View className='selectionInfo'>
        <Text>已选择: {selectedGemIds.length} 个宝石</Text>
      </View>
      
      <View className='modalActions'>
        <Button className='actionBtn confirmBtn' onClick={handleConfirm}>
          确认支付
        </Button>
        <Button className='actionBtn resetBtn' onClick={handleReset}>
          重置
        </Button>
        <Button className='actionBtn cancelBtn' onClick={close}>
          取消
        </Button>
      </View>
    </View>
  );
}